﻿using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;

namespace Utility
{
    public static class FileManager<T>
    {
        public static void Save(string path, List<T> records)
        {
            FileStream fs = null;
            StreamWriter sw = null;

            try
            {
                fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs);

                var serial = JsonConvert.SerializeObject(records, Formatting.Indented);

                sw.WriteLine(serial);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }
            
        }

        public static void SaveAsCustomJSON(string path, List<string> fieldNames,
            List<List<T>> values)
        {
            FileStream fs = null;
            StreamWriter sw = null;

            try
            {
                fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs);

                var nline = values.Count;
                var ncol = fieldNames.Count;

                sw.WriteLine("[");

                for (int i = 0; i < nline; ++i)
                {
                    sw.WriteLine("\t{");

                    for (int j = 0; j < ncol; ++j)
                    {
                        sw.Write("\t\t\"");
                        sw.Write(fieldNames[j]);
                        sw.Write("\" : \"");
                        sw.Write(values[i][j]);
                        sw.Write("\"");

                        if (j != ncol - 1)
                        {
                            sw.Write(",");
                        }

                        sw.WriteLine();
                    }

                    sw.Write("\t}");

                    if (i != nline - 1)
                    {
                        sw.Write(",");
                    }

                    sw.WriteLine();
                }

                sw.WriteLine("]");
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }

        }

        public static List<T> Load(string path)
        {
            FileStream fs = null;
            StreamReader sr = null;

            try
            {
                fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                sr = new StreamReader(fs);

                var content = sr.ReadToEnd();
                var list = JsonConvert.DeserializeObject<List<T>>(content);

                return list;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
    }
}
